package com.molihub.controller;

import com.alibaba.fastjson.JSONObject;
import com.molihub.entity.HomePage;
import com.molihub.entity.ResponseResult;
import com.molihub.entity.User;
import com.molihub.utils.FileUploadUtils;
import com.molihub.utils.LogUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: FileUploadController
 * @Description: 用于图片、音乐等文件上传的控制器
 * @author: GGBOY
 * @date 2020/2/6 23:03
 * @Version: 1.0
 **/
@Controller
public class FileUploadController extends BaseController {

    private Logger logger = LogUtils.getInstance(FileUploadController.class);

    /**
     * 用户头像图片上传
     *
     * @param file 传递过来文件
     * @return java.lang.String
     * @author PJAVAC
     * @date 2020/2/5
     */
    @ResponseBody
    @RequestMapping("/file/imageUpload")
    public ResponseResult imageUpload(@RequestParam("fileName") MultipartFile file) {
        ResponseResult responseResult = new ResponseResult();
        String filename = file.getOriginalFilename();
        try {
            if (file != null) {
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream outputStream = new FileOutputStream(newFile);
                    outputStream.write(file.getBytes());
                    outputStream.close();
                    file.transferTo(newFile);
                    String url = aliyunOssUtil.upLoad(newFile);
                    if (url != null) {
                        //更新用户信息
                        loginUser.setImagePath(url);
                        userService.updateUser(loginUser);
                        responseResult.setSuccess(1);
                        responseResult.setUrl(url);
                        responseResult.setMessage("修改成功!");
                    } else {
                        responseResult.setSuccess(2);
                        responseResult.setMessage("类型错误");
                    }
                    //删除文件
                    newFile.delete();
                }
            }
        } catch (FileNotFoundException e) {
            responseResult.setSuccess(0);
            responseResult.setMessage("上传失败");
            e.printStackTrace();
        } catch (IOException e) {
            responseResult.setSuccess(0);
            responseResult.setMessage("上传失败");
            e.printStackTrace();
        }
        return responseResult;
    }


    /**
     * 用户的头像或者个人主页背景图片上传
     *
     * @param file 上传的图片文件
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/2/6
     */
    @ResponseBody
    @RequestMapping("/profilePage/imageUpload/{flag}")
    public ResponseResult userOrBackgroundImageUpload(@RequestParam("fileName") MultipartFile file, @PathVariable String flag) {
        logger.info("userOrBackgroundImageUpload.... : " + flag + " " + loginUser.toString());
        ResponseResult responseResult = FileUploadUtils.uploadImageWithPost(file);
        if (responseResult != null) {
            if ("0".equals(flag)) {
                // 为 0表示上传的是个人主页的背景图片
                HomePage homePage = new HomePage();
                homePage.setUserId(loginUser.getUserId());
                homePage.setImagePath(responseResult.getUrl());
                homePageService.updateRecord(homePage);
            } else if ("1".equals(flag)) {
                // 为 1表示上传的是个人头像
                //更新用户信息
                User updateUser = new User();
                updateUser.setUserId(loginUser.getUserId());
                updateUser.setImagePath(responseResult.getUrl());
                userService.updateUser(updateUser);
                //更新session中的当前用户
                loginUser.setImagePath(responseResult.getUrl());
            }
        }
        return responseResult;
    }

    /**
     * 主页发表状态时的多图上传
     *
     * @param files 上传的图片
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/2/10
     */
    @ResponseBody
    @PostMapping("/upload/UploadAction")
    public String uploadImageWithPost(@RequestParam("files") MultipartFile[] files) {
        logger.info("uploadImageWithPost>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        List<ResponseResult> list = new ArrayList<>();
        for (MultipartFile file : files) {
            ResponseResult responseResult = FileUploadUtils.uploadImageWithPost(file);
            list.add(responseResult);
        }
        return JSONObject.toJSONString(list);
    }
}
